// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <cantor/transform/exprs/range_var.h>
#include <cantor/transform/expr.h>
#include <cantor/transform/utility.h>

#include "cantor/transform/clause/column_name.h"
#include "cantor/transform/dqls/indirection.h"

namespace cantor::transform {
    void TransRangeVar::resolve_ast(const cantor::parser::RangeVar *node) {
        if (!node) {
            status = turbo::data_loss_error("no expr");
            return;
        }
        if (!node->column) {
            status = turbo::data_loss_error("no column name");
            return;
        }
        status = TransColumnName::resolve_to(node->column, range_var.mutable_column());
        if (!status.ok()) {
            return;
        }

        if (node->indirections.size() >= 1) {
            range_var.mutable_indirections()->Reserve(node->indirections.size());
            for (auto i = 0; i < node->indirections.size(); ++i) {
                auto ind = range_var.mutable_indirections()->Add();
                TransIndirection trans;
                trans.resolve_ast(node->indirections[i]);
                auto &s = trans.check();
                if (!s.ok()) {
                    status = s;
                    return;
                }
                *ind = std::move(trans.indirection);
            }
        }
        set_proto_location(node, range_var.mutable_location());
        set_proto_status(range_var.mutable_status());
    }

    const turbo::Status &TransRangeVar::check() {
        if (!status.ok()) {
            return status;
        }
        if (!range_var.has_location()) {
            make_missing_required_field("location");
            return status;
        }
        return status;
    }

    turbo::Status TransRangeVar::resolve_to(turbo::Nonnull<const cantor::parser::RangeVar *> node,
                                            turbo::Nonnull<pb::ast::RangeVar *> out) {
        TransRangeVar translator;
        translator.resolve_ast(node);
        auto status = translator.check();
        if (!status.ok()) {
            return status;
        }
        *out = std::move(translator.range_var);
        return status;
    }
} // namespace cantor::transform
